using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Markup;
using Common;
using Common.Enum;
using Images;
using Report;
using SExperiment;
using SExperiment.ExperimentResult;
using SSettings;

namespace SettingsView.Search
{
	public partial class UCDataSearch : System.Windows.Controls.UserControl, IComponentConnector, IStyleConnector
	{
		private List<Experiment> targetExperiments;

		private ObservableCollection<SearchData> searchResult = new ObservableCollection<SearchData>();

		public ObservableCollection<string> SellectedFolderPcrList { get; set; }

		public ObservableCollection<string> SearchPcrList { get; set; }

		public UCDataSearch()
		{
			InitializeComponent();
			VirtualizingStackPanel.SetIsVirtualizing((DependencyObject)tvDirectories, false);
			tvDirectories.ItemsSource = DirectoryTree.InitRoot();
			tvDirectories.SelectedItemChanged += tvDirectories_SelectedItemChanged;
			string experimentInitialDirectory = ConfigReader.GetInstance().GetExperimentInitialDirectory();
			if (experimentInitialDirectory == Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory))
			{
				DirectoryTree directoryTree = tvDirectories.ItemsSource.OfType<DirectoryTree>().FirstOrDefault();
				if (directoryTree != null)
				{
					directoryTree.IsSelected = true;
				}
				directoryTree.IsExpanded = true;
			}
			else
			{
				string[] array = experimentInitialDirectory.Split('\\');
				List<string> list = new List<string>();
				string[] array2 = array;
				foreach (string text in array2)
				{
					if (!string.IsNullOrEmpty(text))
					{
						list.Add(text);
					}
				}
				string pathRoot = Path.GetPathRoot(experimentInitialDirectory);
				list[0] = pathRoot;
				List<DirectoryTree> source = tvDirectories.ItemsSource.OfType<DirectoryTree>().ToList();
				for (int j = 0; j < list.Count; j++)
				{
					string name = list[j];
					if (string.IsNullOrEmpty(name))
					{
						continue;
					}
					DirectoryTree directoryTree2 = source.Where((DirectoryTree s) => s.Info.Name == name).FirstOrDefault();
					if (directoryTree2 != null)
					{
						directoryTree2.IsExpanded = true;
						if (j == list.Count - 1)
						{
							directoryTree2.IsSelected = true;
						}
						if (directoryTree2.Directories == null)
						{
							break;
						}
						source = directoryTree2.Directories.ToList();
					}
				}
			}
			tvDirectories.BringIntoView();
			SellectedFolderPcrList = new ObservableCollection<string>();
			SearchPcrList = new ObservableCollection<string>();
			TopList.ItemsSource = SellectedFolderPcrList;
			BottomList.ItemsSource = SearchPcrList;
			cmbType.ItemsSource = EnumManagement.GetAllProjectType();
			cmbType.SelectedValue = EProjectType.AQ;
			List<KeyValuePair> list2 = new List<KeyValuePair>();
			list2.AddRange(EnumManagement.GetAllSampleType());
			list2.Insert(0, new KeyValuePair
			{
				Key = SampleType.All,
				Value = EnumManagement.GetSampleTypeName(SampleType.All)
			});
			sample_type.ItemsSource = list2;
			sample_type.SelectedValue = SampleType.All;
			GridColumns gridColumns = ConfigSettings.GetInstance().AQColumns.Clone();
			if (gridColumns != null)
			{
				gridColumns.Columns.Add(new ColumnInfo
				{
					FieldName = "Search.Result.FileName",
					Header = Utility.GetMessage("file_name"),
					AllowDelete = false,
					AllowEditing = true
				});
				SearchResultInfo.GridColumns = gridColumns;
			}
			SearchResultInfo.Refresh();
		}

		private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
		{
			FrameworkElement frameworkElement = sender as FrameworkElement;
			frameworkElement.BringIntoView();
		}

		private void tvDirectories_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
		{
			SellectedFolderPcrList.Clear();
			System.Windows.Controls.TreeView treeView = sender as System.Windows.Controls.TreeView;
			if (treeView == null || treeView.SelectedItem == null)
			{
				return;
			}
			DirectoryTree directoryTree = treeView.SelectedItem as DirectoryTree;
			if (directoryTree == null)
			{
				return;
			}
			string fullName = directoryTree.Info.FullName;
			try
			{
				string[] files = Directory.GetFiles(fullName, "*." + Experiment.FileExt, SearchOption.TopDirectoryOnly);
				if (files.Length > 0)
				{
					string[] array = files;
					foreach (string item in array)
					{
						SellectedFolderPcrList.Add(item);
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private void Button_Serach_Click(object sender, RoutedEventArgs e)
		{
			EProjectType selType = EProjectType.AQ;
			if (cmbType.SelectedValue != null)
			{
				selType = (EProjectType)cmbType.SelectedValue;
				GridColumns girdColumnsClone = ConfigSettings.GetInstance().GetGirdColumnsClone(selType);
				if (girdColumnsClone != null)
				{
					girdColumnsClone.Columns.Add(new ColumnInfo
					{
						FieldName = "Search.Result.FileName",
						Header = Utility.GetMessage("file_name"),
						AllowDelete = false,
						AllowEditing = true
					});
					SearchResultInfo.GridColumns = girdColumnsClone;
				}
			}
			targetExperiments = new List<Experiment>();
			searchResult.Clear();
			foreach (string searchPcr in SearchPcrList)
			{
				Experiment experiment = Experiment.Load(searchPcr, false);
				if (experiment != null)
				{
					if (string.Compare(experiment.UpdateVersion, "8.2.2.50603") < 0)
					{
						DumpInvoke.DataAnalyse(experiment, false);
					}
					targetExperiments.Add(experiment);
				}
			}
			IEnumerable<Experiment> source = targetExperiments;
			if (!string.IsNullOrEmpty(experiment_name.Text))
			{
				source = source.Where((Experiment s) => s.Name == experiment_name.Text);
			}
			if (!string.IsNullOrEmpty(experiment_operator.Text))
			{
				source = source.Where((Experiment s) => s.Operator == experiment_operator.Text);
			}
			if (!string.IsNullOrEmpty(experiment_auditor.Text))
			{
				source = source.Where((Experiment s) => s.Auditor == experiment_auditor.Text);
			}
			if (inspection_date.SelectedDate.HasValue)
			{
				source = source.Where(delegate(Experiment s)
				{
					s.GetInspectionDate();
					return true;
				}).Where(delegate(Experiment s)
				{
					DateTime inspectionDate = s.GetInspectionDate();
					DateTime? selectedDate = inspection_date.SelectedDate;
					return inspectionDate > selectedDate;
				});
			}
			if (inspection_date2.SelectedDate.HasValue)
			{
				source = source.Where(delegate(Experiment s)
				{
					s.GetInspectionDate();
					return true;
				}).Where(delegate(Experiment s)
				{
					DateTime inspectionDate2 = s.GetInspectionDate();
					DateTime? selectedDate2 = inspection_date2.SelectedDate;
					return inspectionDate2 < selectedDate2;
				});
			}
			source = source.Where((Experiment s) => s.Type == selType);
			foreach (Experiment item in source)
			{
				IEnumerable<Well> enumerable = item.Wells.Where((Well w) => w.Sample != null);
				if (!string.IsNullOrEmpty(project.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.Project.BasicInfo.Name == project.Text);
				}
				if (!string.IsNullOrEmpty(sample_index.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.ID == sample_index.Text);
				}
				if (!string.IsNullOrEmpty(sample_case_id.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.CaseID == sample_case_id.Text);
				}
				if (!string.IsNullOrEmpty(sample_doctor.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.Doctor == sample_doctor.Text);
				}
				if (!string.IsNullOrEmpty(patient_name.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.Name == patient_name.Text);
				}
				if (!string.IsNullOrEmpty(sample_bed_id.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.BedID == sample_bed_id.Text);
				}
				if (!string.IsNullOrEmpty(sample_office.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.Office == sample_office.Text);
				}
				if (!string.IsNullOrEmpty(sample_sex.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.Sex == sample_sex.Text);
				}
				if (!string.IsNullOrEmpty(sample_inpatient_id.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.InPatientID == sample_inpatient_id.Text);
				}
				if (!string.IsNullOrEmpty(sample_age.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.Age == sample_age.Text);
				}
				if (!string.IsNullOrEmpty(sample_outpatient_id.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.OutPatientID == sample_outpatient_id.Text);
				}
				if (!string.IsNullOrEmpty(sample_specimen.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.Specimen == sample_specimen.Text);
				}
				if (!string.IsNullOrEmpty(sample_diagnosis.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.PatientInfo.Diagnosis.Contains(sample_diagnosis.Text));
				}
				if (sample_specimen_date.SelectedDate.HasValue)
				{
					enumerable = enumerable.Where((Well s) => !string.IsNullOrEmpty(s.Sample.PatientInfo.SpecimenDate)).Where(delegate(Well s)
					{
						DateTime value = DateTime.Parse(s.Sample.PatientInfo.SpecimenDate);
						DateTime? selectedDate3 = sample_specimen_date.SelectedDate;
						return value > selectedDate3;
					});
				}
				if (sample_specimen_date2.SelectedDate.HasValue)
				{
					enumerable = enumerable.Where((Well s) => !string.IsNullOrEmpty(s.Sample.PatientInfo.SpecimenDate)).Where(delegate(Well s)
					{
						DateTime value2 = DateTime.Parse(s.Sample.PatientInfo.SpecimenDate);
						DateTime? selectedDate4 = sample_specimen_date2.SelectedDate;
						return value2 < selectedDate4;
					});
				}
				if (!string.IsNullOrEmpty(Prj_SampleConclusion.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.Result.ConclusionList.Where((Conclusion x) => x.Content.Contains(Prj_SampleConclusion.Text)).Count() > 0);
				}
				if (sample_type.SelectedValue != null && (SampleType)sample_type.SelectedValue != SampleType.All)
				{
					enumerable = enumerable.Where((Well s) => s.Sample.Items.Where((SampleTargetItem x) => x.SampleType == (SampleType)sample_type.SelectedValue).Count() > 0);
				}
				if (!string.IsNullOrEmpty(sample_property.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.Items.Where((SampleTargetItem x) => x.Property == sample_property.Text).Count() > 0);
				}
				if (!string.IsNullOrEmpty(Prj_TargetInfo.Text))
				{
					enumerable = enumerable.Where((Well s) => s.Sample.Items.Where((SampleTargetItem x) => x.TargetName == Prj_TargetInfo.Text).Count() > 0);
				}
				if (enumerable.Count() <= 0)
				{
					continue;
				}
				double result = double.NaN;
				if (!string.IsNullOrEmpty(Ct.Text))
				{
					double.TryParse(Ct.Text, out result);
				}
				double result2 = double.NaN;
				if (!string.IsNullOrEmpty(Ct2.Text))
				{
					double.TryParse(Ct2.Text, out result2);
				}
				double result3 = double.NaN;
				if (!string.IsNullOrEmpty(Cn.Text))
				{
					double.TryParse(Cn.Text, out result3);
				}
				double num = double.NaN;
				if (!string.IsNullOrEmpty(Cn2.Text))
				{
					double.TryParse(Cn2.Text, out result2);
				}
				foreach (Well item2 in enumerable)
				{
					if (item2.Sample == null || item2.MultiTubeID != 1)
					{
						continue;
					}
					foreach (SampleTargetItem item3 in item2.Sample.Items)
					{
						bool flag = true;
						if (double.IsPositiveInfinity(item3.Result.CtValue))
						{
							flag = Ct_CheckBox.IsChecked.Value;
						}
						else if (!double.IsNaN(result) && double.IsNaN(result2))
						{
							flag = ((item3.Result.CtValue >= result) ? true : false);
						}
						else if (double.IsNaN(result) && !double.IsNaN(result2))
						{
							flag = ((item3.Result.CtValue <= result2) ? true : false);
						}
						else if (!double.IsNaN(result) && !double.IsNaN(result2))
						{
							flag = ((item3.Result.CtValue >= result && item3.Result.CtValue <= result2) ? true : false);
						}
						if (!flag)
						{
							continue;
						}
						if (!double.IsNaN(result3) && double.IsNaN(num))
						{
							flag = ((item3.Result.CnValue >= result3) ? true : false);
						}
						else if (double.IsNaN(result3) && !double.IsNaN(num))
						{
							flag = ((item3.Result.CnValue <= num) ? true : false);
						}
						else if (!double.IsNaN(result3) && !double.IsNaN(num))
						{
							flag = ((item3.Result.CnValue >= result3 && item3.Result.CnValue <= num) ? true : false);
						}
						if (flag)
						{
							SearchData searchData = new SearchData();
							searchData.Item = item3;
							if (item.Subsets.Count() > 0)
							{
								searchData.Subset = item.Subsets[0];
							}
							searchData.FileName = item.FilePath;
							searchData.Well = item2.Sample.Wells[item3.TubeNo - 1];
							searchResult.Add(searchData);
						}
					}
				}
			}
			SearchResultInfo.SearchDatas = searchResult;
			SearchResultInfo.Refresh();
		}

		private void Button_Reset_Click(object sender, RoutedEventArgs e)
		{
			if (System.Windows.MessageBox.Show(Utility.GetMessage("msg_reset_confirm"), Utility.GetMessage("Warning"), MessageBoxButton.YesNo) != MessageBoxResult.Yes)
			{
				return;
			}
			IEnumerable<System.Windows.Controls.TextBox> enumerable = searchGrid.Children.OfType<System.Windows.Controls.TextBox>();
			foreach (System.Windows.Controls.TextBox item in enumerable)
			{
				item.Text = string.Empty;
			}
			Ct.Text = string.Empty;
			Ct2.Text = string.Empty;
			Cn.Text = string.Empty;
			Cn2.Text = string.Empty;
			Ct_CheckBox.IsChecked = true;
			sample_type.SelectedValue = SampleType.All;
			cmbType.SelectedValue = EProjectType.AQ;
			sample_specimen_date.SelectedDate = null;
			sample_specimen_date2.SelectedDate = null;
			inspection_date.SelectedDate = null;
			inspection_date2.SelectedDate = null;
		}

		private void Button_Save_Click(object sender, RoutedEventArgs e)
		{
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			saveFileDialog.Title = Utility.GetMessage("Save");
			saveFileDialog.Filter = string.Format("{1}{0}|*.{2}", Utility.GetMessage("File"), "Excel", "xlsx");
			saveFileDialog.FilterIndex = 1;
			saveFileDialog.InitialDirectory = Utility.GetMyDocumentFolder();
			if (saveFileDialog.ShowDialog() == DialogResult.OK)
			{
				base.Cursor = System.Windows.Input.Cursors.Wait;
				int filterIndex = saveFileDialog.FilterIndex;
				if (filterIndex == 1)
				{
					SaveSelectedDataToExcel(saveFileDialog.FileName);
				}
				base.Cursor = System.Windows.Input.Cursors.Arrow;
				System.Windows.MessageBox.Show(Utility.GetMessage("msg_data_export_sussess"));
			}
		}

		public void SaveSelectedDataToExcel(string file)
		{
			ExcelData excelData = new ExcelData();
			ExcelSheetData excelSheetData = new ExcelSheetData();
			excelSheetData.Name = Utility.GetMessage("well_info_table");
			excelSheetData.Data = SearchResultInfo.GetData(null, false, true);
			excelData.SheetDataList.Add(excelSheetData);
			ExcelOperator.SaveToExcel(file, excelData);
		}

		private void Button_Inster_Click(object sender, RoutedEventArgs e)
		{
			if (TopList.SelectedItems.Count > 0)
			{
				string item = TopList.SelectedItem as string;
				if (!SearchPcrList.Contains(item))
				{
					SearchPcrList.Add(item);
				}
			}
		}

		private void Button_InsterAll_Click(object sender, RoutedEventArgs e)
		{
			foreach (string sellectedFolderPcr in SellectedFolderPcrList)
			{
				if (!SearchPcrList.Contains(sellectedFolderPcr))
				{
					SearchPcrList.Add(sellectedFolderPcr);
				}
			}
		}

		private void Button_Delete_Click(object sender, RoutedEventArgs e)
		{
			if (BottomList.SelectedItems.Count > 0)
			{
				string item = BottomList.SelectedItem as string;
				if (SearchPcrList.Contains(item))
				{
					SearchPcrList.Remove(item);
				}
			}
		}

		private void Button_DeleteAll_Click(object sender, RoutedEventArgs e)
		{
			if (SearchPcrList.Count() > 0)
			{
				SearchPcrList.Clear();
			}
		}

		public List<SearchData> GetSelectedData()
		{
			return SearchResultInfo.GetSelectedData();
		}

		[DebuggerNonUserCode]
		[GeneratedCode("PresentationBuildTasks", "4.0.0.0")]
		internal Delegate _CreateDelegate(Type delegateType, string handler)
		{
			return Delegate.CreateDelegate(delegateType, this, handler);
		}
	}
}
